#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/esb/apps/manager/channel/views.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import json
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic import View
from django.http import Http404
from common.log import logger
from esb.bkcore.models import ESBChannel
from esb.common.decorators import is_user_super
from esb.configs.default import menu_items
from .forms import ESBChannelForm, EditESBChannelForm
from ..system.forms import ComponentSystemForm
from ..utils import md2html
menu_active_item = 'channel_manager'

class ChannelListView(View):
    """Channel list page"""

    @is_user_super
    def get(self, request):
        channel_exists = ESBChannel.objects.exists()
        systems = [{'name': '','label': u'全部'}]
        systems.extend([ {'name': system['component_system__name'],'label': u'[%s] %s' % (system['component_system__name'], system['component_system__label'])} for system in ESBChannel.objects.order_by('component_system__name').values('component_system__name', 'component_system__label').distinct()
                       ])
        return render(request, 'manager/channel/list.html', {'channel_exists': channel_exists,
           'systems': systems,
           'menu_items': menu_items,
           'menu_active_item': menu_active_item,
           'channel_term_html': md2html('channel')
           })


class AddChannelView(View):
    """Add channel view"""

    @is_user_super
    def get(self, request):
        form = ESBChannelForm()
        system_form = ComponentSystemForm()
        return render(request, 'manager/channel/add.html', {'form': form,
           'system_form': system_form,
           'menu_items': menu_items,
           'menu_active_item': menu_active_item
           })

    @is_user_super
    def post(self, request):
        form = ESBChannelForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('manager.channel.list'))
        system_form = ComponentSystemForm()
        return render(request, 'manager/channel/add.html', {'form': form,
           'system_form': system_form,
           'menu_items': menu_items,
           'menu_active_item': menu_active_item
           })


class EditChannelView(View):
    """Edit channel view"""

    @is_user_super
    def get(self, request, channel_id):
        if not str(channel_id).isdigit():
            raise Http404
        channel = ESBChannel.objects.get(id=channel_id)
        form = EditESBChannelForm(instance=channel)
        system_form = ComponentSystemForm()
        try:
            if channel.comp_conf:
                comp_conf = json.loads(channel.comp_conf)
            else:
                comp_conf = None
        except:
            logger.error('esb channel comp_conf is not json, channel_id: %s, comp_conf: %s', channel_id, channel.comp_conf)
            comp_conf = None

        _comp_conf_group = self.comp_conf_group(channel.path, comp_conf)
        if _comp_conf_group:
            _comp_conf_val = json.dumps([ (conf['key'], conf['value']) for conf in _comp_conf_group['comp_conf'] ])
        else:
            _comp_conf_val = ''
        return render(request, 'manager/channel/edit.html', {'form': form,
           'system_form': system_form,
           'menu_items': menu_items,
           'menu_active_item': menu_active_item,
           'comp_conf': comp_conf,
           'comp_conf_val': _comp_conf_val,
           'comp_conf_group': _comp_conf_group
           })

    @is_user_super
    def post(self, request, channel_id):
        channel = ESBChannel.objects.get(id=channel_id)
        form = EditESBChannelForm(request.POST, instance=channel)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('manager.channel.list'))
        system_form = ComponentSystemForm()
        return render(request, 'manager/channel/edit.html', {'form': form,
           'system_form': system_form,
           'menu_items': menu_items,
           'menu_active_item': menu_active_item
           })

    def comp_conf_group(self, path, comp_conf):
        """
        注意：生成结果的 comp_conf 中不能有 key 值相同的项，否则，数据库中 comp_conf 也会出现多余的重复字段
        """
        if not comp_conf:
            return None
        if path == '/cmsi/send_weixin/':
            comp_conf = dict(comp_conf)
            return {'group_field': 'wx_type',
               'groups': [{'value': 'qywx','label': u'企业微信'}, {'value': 'qy','label': u'微信企业号'}, {'value': 'mp','label': u'微信公众号'}],'comp_conf': [
                           {'key': 'wx_type',
                              'value': comp_conf.get('wx_type', '')
                              },
                           {'key': 'wx_app_id',
                              'value': comp_conf.get('wx_app_id', ''),
                              'group': 'wx_type wx_type_mp'
                              },
                           {'key': 'wx_secret',
                              'value': comp_conf.get('wx_secret', ''),
                              'group': 'wx_type wx_type_mp',
                              'text_type': 'password'
                              },
                           {'key': 'wx_token',
                              'value': comp_conf.get('wx_token', ''),
                              'group': 'wx_type wx_type_mp',
                              'text_type': 'password'
                              },
                           {'key': 'wx_template_id',
                              'value': comp_conf.get('wx_template_id', ''),
                              'group': 'wx_type wx_type_mp'
                              },
                           {'key': 'wx_qy_corpid',
                              'value': comp_conf.get('wx_qy_corpid', ''),
                              'group': 'wx_type wx_type_qy wx_type_qywx'
                              },
                           {'key': 'wx_qy_corpsecret',
                              'value': comp_conf.get('wx_qy_corpsecret', ''),
                              'group': 'wx_type wx_type_qy wx_type_qywx',
                              'text_type': 'password'
                              },
                           {'key': 'wx_qy_agentid',
                              'value': comp_conf.get('wx_qy_agentid', ''),
                              'group': 'wx_type wx_type_qy wx_type_qywx'
                              }]
               }
        if path == '/cmsi/send_mail/':
            comp_conf = dict(comp_conf)
            return {'comp_conf': [
                           {'key': 'dest_url',
                              'value': comp_conf.get('dest_url', '')
                              },
                           {'key': 'smtp_host',
                              'value': comp_conf.get('smtp_host', '')
                              },
                           {'key': 'smtp_port',
                              'value': comp_conf.get('smtp_port', 25)
                              },
                           {'key': 'smtp_user',
                              'value': comp_conf.get('smtp_user', '')
                              },
                           {'key': 'smtp_pwd',
                              'value': comp_conf.get('smtp_pwd', ''),
                              'text_type': 'password'
                              },
                           {'key': 'smtp_usessl',
                              'value': comp_conf.get('smtp_usessl', 'False')
                              },
                           {'key': 'mail_sender',
                              'value': comp_conf.get('mail_sender', '')
                              }]
               }
        if path == '/cmsi/send_sms/':
            comp_conf = dict(comp_conf)
            return {'comp_conf': [
                           {'key': 'dest_url',
                              'value': comp_conf.get('dest_url', '')
                              },
                           {'key': 'qcloud_app_id',
                              'value': comp_conf.get('qcloud_app_id', '')
                              },
                           {'key': 'qcloud_app_key',
                              'value': comp_conf.get('qcloud_app_key', ''),
                              'text_type': 'password'
                              }]
               }
        comp_conf = [ {'key': key,'value': value} for key, value in comp_conf
                    ]
        return {'comp_conf': comp_conf}
